// pages/history/history.js
const storage = require('../../utils/storage.js');

Page({
  data: {
    history: [],
    filteredHistory: [],
    filterType: 'all',
    stats: {}
  },

  onLoad(options) {
    // 处理从个人中心传入的过滤参数
    if (options.filter && ['all', 'manual', 'auto'].includes(options.filter)) {
      this.setData({
        filterType: options.filter
      });
    }
    
    this.loadHistory();
    this.loadStatistics();
  },

  /**
   * 加载游戏历史
   */
  loadHistory() {
    const history = storage.getGameHistory();
    
    // 格式化数据
    const formattedHistory = history.map(item => ({
      ...item,
      dateFormatted: storage.formatDateTime(item.timestamp),
      durationFormatted: storage.formatDuration(item.duration),
      difficultyText: this.getDifficultyText(item.difficulty)
    }));
    
    this.setData({
      history: formattedHistory
    });

    // 应用当前过滤器
    this.applyFilter();
  },

  /**
   * 加载统计数据
   */
  loadStatistics() {
    const stats = storage.getStatistics();
    
    this.setData({
      stats: {
        ...stats,
        avgTimeFormatted: storage.formatDuration(stats.avgTime)
      }
    });
  },

  /**
   * 筛选类型改变
   */
  onFilterChange(e) {
    const { type } = e.currentTarget.dataset;
    this.setData({
      filterType: type
    });
    this.applyFilter();
  },

  /**
   * 应用过滤器
   */
  applyFilter() {
    let filteredHistory = this.data.history;
    
    if (this.data.filterType === 'auto') {
      filteredHistory = this.data.history.filter(item => item.solveType === 'auto');
    } else if (this.data.filterType === 'manual') {
      filteredHistory = this.data.history.filter(item => item.solveType === 'manual');
    }
    
    this.setData({
      filteredHistory
    });
  },

  /**
   * 返回上一页
   */
  onBack() {
    wx.navigateBack();
  },

  /**
   * 获取难度文字
   */
  getDifficultyText(difficulty) {
    const map = {
      'easy': '简单',
      'medium': '中等',
      'hard': '困难'
    };
    return map[difficulty] || '中等';
  }
});
